package com.ljw.practice;

import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JPanel;
import javax.swing.Timer;

import org.apache.log4j.Logger;

public class MyBoard6 extends JPanel implements ActionListener{
	private Logger logger = Logger.getLogger(MyBoard6.class);
	private static int REFREAH_TERM = 30;
	
	MyCraft craft;
	
	public MyBoard6(){
		initUI();
		initEvent();
		engineStart();
	}

	private void engineStart() {
		new Thread(){
			public  void run(){
				
				long beforeTime = System.currentTimeMillis();
				long startTime = System.currentTimeMillis();
				long sleep = 0;
				
				try{
					while(true){
						logger.info("while");
						
						startTime = System.currentTimeMillis();
						sleep = beforeTime - startTime;
						
						if(sleep < 0 || sleep >= MyBoard6.REFREAH_TERM)
							sleep = 0;
						else
							sleep = MyBoard6.REFREAH_TERM;
						
						Thread.sleep(sleep);
						logger.info("sleep time : " + sleep);
						
						//graphicEngine();
						
						craft.move();
						repaint();
						//Toolkit.getDefaultToolkit().sync();
						
						beforeTime = System.currentTimeMillis();
					}
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void initUI() {
		craft = new MyCraft();
		setFocusable(true);
	}
	
	private void initEvent() {
		addKeyListener(new MyKeyAdapter());
	}
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		drawImage(g);
		
		logger.info("paintComponent");
	}

	private void drawImage(Graphics g) {
		logger.info("drawImage");
		g.drawImage(craft.getCraft(), craft.getX(), craft.getY(), null);
	}
	
	public void graphicEngine(){
		logger.info("graphicEngine");
		craft.move();
		repaint();
		Toolkit.getDefaultToolkit().sync();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		craft.move();
		repaint();
	}
	
	public class MyKeyAdapter extends KeyAdapter{
		public MyKeyAdapter(){		
		}
		
		@Override
		public void keyPressed(KeyEvent e){
			logger.info("keyPressed: " + e.getKeyCode() );
			craft.keyPressed(e);
		}
		
		@Override
		public void keyReleased(KeyEvent e){
			logger.info("keyReleassed: " + e.getKeyCode() );
			craft.keyReleased(e);
		}
	}
}